﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using System.Threading;
using Common;
using Common.Models;
using Microsoft.VisualBasic;
using Test;

namespace Painter
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 画图数据计数
        /// </summary>
        int n = 0;
        /// <summary>
        /// 计算需要的数据
        /// </summary>
        public static List<Common.Models.Input> Inputs = new List<Common.Models.Input>();

        /// <summary>
        /// 所有画图输出模型
        /// </summary>
        public static List<Output> Outputs = new List<Output>();
        /// <summary>
        /// 文件路径
        /// </summary>
        private static string _filePath;
        public class FileReadException : System.Exception
        {
            public FileReadException(string message) : base("文件" + message + "格式错误！")
            {
            }
        }
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 打开文件选择框设置文件路径返回选择结果
        /// </summary>
        public static bool OpenFileDialog()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "输入文本文件（*.txt）|*.txt";

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                _filePath = ofd.FileName;
                return true;
            }
            return false;
        }
        private void Open(Form childForm)
        {
            //遍历子窗口，如果存在打开,关闭其他子窗口
            foreach (var item in MdiChildren)
            {
                if (item.Name == childForm.Name)
                {
                    childForm = item;
                    break;
                }
                else
                {
                    item.Close();
                }
            }
            childForm.MdiParent = this;
            childForm.Show();
        }
        /// <summary>
        /// qwe计算
        /// </summary>
        private void QWECalc(int patternType)
        {
            var task = Task.Run(() =>
            {
                Parallel.For(0, Inputs.Count, i => testqwe.Program.Start(Inputs[i], patternType, ref Outputs)
                );
            });
            task.ContinueWith((o) =>
            {
                MessageBox.Show("qwe计算完成");
            });
            开始画图ToolStripMenuItem.Enabled = true;
        }

        void SGHCalc(int patternType)
        {
            if (Inputs.Count < 1)
            {
                MessageBox.Show("没有输入数据！");
                return;
            }
            var paras = "";
            if (patternType==3)
            {
                paras = Interaction.InputBox("请输入余料长度限制和种类限制，以逗号隔开\r\n500,10", "余料参数设置", "", 100, 100);
                if (string.IsNullOrWhiteSpace(paras))
                {
                    paras = "500,10";
                }
            }
            var task = Task.Run(() =>
              {
                  
                  Parallel.For(0, Inputs.Count, i => new SGH.Program().Start(Inputs[i], patternType, ref Outputs,paras)
                  );
              });
            task.ContinueWith(o =>
            {
                MessageBox.Show("sgh计算完成");
            });
            开始画图ToolStripMenuItem.Enabled = true;
        }

       private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        private void 开始画图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Open(new Picture());
            var count = Outputs.Count;
            if (count < 1)
            {
                return;
            }

            if (开始画图ToolStripMenuItem.Text == "开始画图")
            {
                n = 0;
                if (n + 1 != count)
                {
                    开始画图ToolStripMenuItem.Text = "下一组";
                }

            }
            else if (开始画图ToolStripMenuItem.Text == "下一组")
            {
                n++;
                if (n + 1 == count)
                {
                    开始画图ToolStripMenuItem.Text = "开始画图";
                }

            }
            if (count > 0)
            {
                toolStripStatusLabel1.Text = "第" + (n + 1) + "组,共" + count + "组";
                var bmp=   Draw.OutputToBitmap(Outputs[n]);
                //var height = (3400 + (int)Math.Ceiling(Outputs[n].Plates.Count / 5.0) * (int)Outputs[n].Width * 2) / 10;
                //var width = (int)Outputs[n].Length * 6 / 10;
                //var bmp = new Bitmap(width, height);
                //var g1 = Graphics.FromImage(bmp);
                //DrawPattern(Outputs[n], g1);
                //g1.Dispose();
                var FormPicture = this.MdiChildren.Where(o => o.Name == new Picture().Name).ToArray()[0];
                var pictureBox1 = FormPicture.Controls.Find("pictureBox1", true);
                if (pictureBox1.Length > 0)
                    (pictureBox1[0] as PictureBox).Image = bmp;
            }
            else
            {
                MessageBox.Show("暂时没有数据！");
            }


        }

        private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var isOpen = OpenFileDialog();
            if (isOpen)
            {
                var str = ReadInput.GetStr(_filePath);
                if (!string.IsNullOrEmpty(str))
                {
                    ReadInput.ReadDraw(str, ref Outputs);
                    开始画图ToolStripMenuItem.Enabled = true;
                    MessageBox.Show("读取完成！");
                }
                else
                {
                    MessageBox.Show("请重新选择！");
                }
            }
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            Array aryFiles = (System.Array)e.Data.GetData(DataFormats.FileDrop);
            int i = 0;
            while (i < aryFiles.Length)
            {
                if (!aryFiles.GetValue(i).ToString().EndsWith(".txt"))
                {
                    MessageBox.Show("文件 “" + aryFiles.GetValue(i).ToString() + "”无效！！");
                    return;
                }

                StreamReader sr = new StreamReader(aryFiles.GetValue(i).ToString(), Encoding.UTF8);
                string str = sr.ReadToEnd();
                ReadInput.ReadDraw(str, ref Outputs);
                sr.Close();
                i++;
                开始画图ToolStripMenuItem.Enabled = true;

            }
            MessageBox.Show("读取完毕!");
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;
        }


        private void 全部保存ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Outputs.Count == 0)
            {
                MessageBox.Show("暂无数据！"); return;
            }
            string path;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "JPEG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp|PNG(*.png)|*.png";
            if ((sfd.FileName != null) && sfd.ShowDialog() == DialogResult.OK)
            {

                for (int i = 0; i < Outputs.Count; i++)
                {
                    path = sfd.FileName;
                    //Bitmap bmp = new Bitmap(1382, 744);
                    //Graphics g = Graphics.FromImage(bmp);
                    //DrawPattern(Outputs[n], g);
                    //g.Dispose();
                    var bmp = Draw.OutputToBitmap(Outputs[n]);

                    path = path.Insert(path.IndexOf('.'), i.ToString());
                    bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                }

                MessageBox.Show("保存成功！");
            }
            else
            {
                return;
            }
        }

        private void 另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Outputs.Count == 0)
            {
                MessageBox.Show("暂无数据！"); return;
            }
            string path;
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "JPEG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp|PNG(*.png)|*.png";
            if ((sfd.FileName != null) && sfd.ShowDialog() == DialogResult.OK)
            {
                path = sfd.FileName;
                //Bitmap bmp = new Bitmap(1400, Constant.bmp);
                //Graphics g = Graphics.FromImage(bmp);
                //DrawPattern(Outputs[n], g);
                //g.Dispose();

                var bmp = Draw.OutputToBitmap(Outputs[n]);
                var FormPicture = this.MdiChildren.Where(o => o.Name == new Picture().Name).ToArray()[0];
                var pictureBox1 = FormPicture.Controls.Find("pictureBox1", true);
                if (pictureBox1.Length > 0)
                    
                bmp = (Bitmap) (pictureBox1[0] as PictureBox).Image;
                bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png);
                MessageBox.Show("保存成功！");
            }
            else
            {
                return;
            }
        }
        private void doTestForOneToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SGHCalc(0);
        }

        private void doTestToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SGHCalc(1);
        }

        private void sGHToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SGHCalc(2);
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //pictureBox1.Height = this.Height ;
            //pictureBox1.Width = this.Width;
            ////pictureBox1.SetBounds(0, 25, this.Height, this.Width);
        }


        private void 清除画图数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Outputs.Clear();
            if (!Outputs.Any())
            {
                n = 0;
                开始画图ToolStripMenuItem.Text = "开始画图";
                开始画图ToolStripMenuItem.Enabled = false;
                MessageBox.Show("清除成功");

            }
        }

        private void 清除计算数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Inputs.Clear();
            MessageBox.Show("清除成功！");
        }

        private void 对称ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QWECalc(0);
        }

        private void 不对称计算ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            QWECalc(1);
        }

        private void 输入ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Open(new Input());
        }

        private void 保存文本ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Outputs.Count == 0 && Inputs.Count == 0)
            {
                MessageBox.Show("暂无数据！"); return;
            }
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "txt(*.txt)|*.txt";
            if ((sfd.FileName != null) && sfd.ShowDialog() == DialogResult.OK)
            {
                var num = 0;
                foreach (var item in Inputs)
                {
                    var sw = File.CreateText(sfd.FileName.TrimEnd('.', 't', 'x') + "_Calc" + num + ".txt");
                    sw.WriteLine("[" + item.Length + "," + item.Width + "," + item.Num + "]");
                    for (int i = 0; i < item.Num; i++)
                    {
                        var dia = item.Diameter[i];
                        var dem = item.Demand[i];
                        sw.WriteLine("[" + dia + "," + dem + "]");
                    }
                    sw.Flush();
                    sw.Dispose();
                    num++;
                }
                for (int i = 0; i < Outputs.Count; i++)
                {
                    var sw = File.CreateText(sfd.FileName.TrimEnd('.', 't', 'x') + "_Result" + i + ".txt");
                    sw.WriteLine($"Length:{Outputs[i].Length}");
                    sw.WriteLine($"Width:{Outputs[i].Width}");
                    sw.WriteLine("DiaTotalNum:" + Outputs[i].Num);
                    sw.Write("Diameter:");
                    foreach (var item in Outputs[i].Diameter)
                    {
                        sw.Write($" {item}");
                    }
                    sw.WriteLine();
                    sw.Write("Demand:");
                    foreach (var item in Outputs[i].Demand)
                    {
                        sw.Write($" {item}");
                    }
                    sw.WriteLine();
                    sw.WriteLine("DiaNum:");
                    foreach (var diaList in Outputs[i].DiaNum)
                    {
                        sw.Write($"{"",8}");
                        foreach (var item in diaList)
                        {
                            sw.Write($"{item,-4}");
                        }
                        sw.WriteLine();
                    }

                    foreach (var t in Outputs[i].Plates)
                    {
                        sw.WriteLine("!");
                        foreach (var plate in t)
                        {
                            foreach (var data in plate)
                            {
                                sw.WriteLine(data[0] + " " + data[1] + " " + data[2] + " " + data[3] + " " + data[4] + " " + data[5] + " " + data[6]);
                            }
                        }
                    }
                    sw.WriteLine("!");
                    sw.WriteLine($"TotalPlateNum:{Outputs[i].TotalPlateNum}");
                    sw.WriteLine($"UtilizationRate:{Outputs[i].UtilizationRate}");
                    sw.WriteLine("#");
                    sw.Flush();
                    sw.Dispose();
                }

                MessageBox.Show("保存成功！");
            }
            else
            {
                return;
            }
        }

        private void 帮助ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Open(new Help());
        }

        private void 测试ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //UnitTest1.Regex();
        }

        private void sgh余料控制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SGHCalc(3);
        }
    }
}

